package com.andkrup.easygame.config {
	import com.andkrup.easygame.game.commands.IGameCommand;	
	
	/**
	 * @author Andkrup
	 * 
	 * A KeyConfiguration is a collection of the commands a user can impose on a
	 * game character. Examples could be: "Shoot", "Run left", etc.
	 * 
	 * An instance of this class serves as a list of what buttons makes the game
	 * character do something. By adding more commands to this list the game has
	 * more commands available (ofcourse the game logic should support those
	 * commands).
	 * 
	 * This class saves commands in a lookup hash for speed
	 */
	public class KeyConfiguration {

		private var mapping:Object;
		private var _enabled : Boolean;

		public function get enabled():Boolean{
			return _enabled;
		}
		public function set enabled(value:Boolean):void{
			_enabled = value;
		}
		
		public function KeyConfiguration(){
			mapping = {};
			enabled = true;
		}
		
		public function getGameCommand(char:String, event:String):IGameCommand{
			if(!enabled){
				return null;
			}
			if(!mapping[event]){
				return null;
			}
			return mapping[event][char] as IGameCommand;
		}
		
		public function addCommand(cmd:IGameCommand):void{
			if(!contains(cmd)){
				if(!mapping[cmd.eventType]){
					mapping[cmd.eventType] = {};
				}
				mapping[cmd.eventType][cmd.code] = cmd;
				trace("KeyConfiguration:> getGameCommand() mapping["+cmd.eventType+"]["+cmd.code+"]: "+mapping[cmd.eventType][cmd.code]);
			}
		}
		public function removeCommand(cmd:IGameCommand):void{
			var commands:Object = mapping[cmd.eventType] as Object;
			if(!commands){
				return;
			}
			mapping[cmd.eventType][cmd.code] = undefined;
			var c:uint = 0;
			for(var str:String in commands){
				if(commands[str]){
					c++;
				}
			}
			if(c==0){
				mapping[cmd.eventType] = undefined;
			}
		}
		public function contains(cmd:IGameCommand):Boolean{
			var commands:Object = mapping[cmd.eventType] as Object;
			if(!commands){
				mapping[cmd.eventType] = [];
				return false;
			}
			for each(var command:IGameCommand in commands){
				if(command.equals(cmd)){
					return true;
				}
			}
			return false;
		}
	}
}
